<template>
  <el-col :span="span">
    <el-form-item
      :label="label"
      class="address-wrapper is-required"
    >
      <el-form-item           
        :prop=" props.prop + '.' + customKey.province"
        :rules="[{ required: true, message: '请选择省份', trigger: 'change', }]"
      >
        <el-select
          ref="provinceLabel"
          v-model="formData[customKey.province]"
          placeholder="选择省"
          :disabled="readonly"
          @change="provinceChange($event)"
        >
          <el-option v-for="item in provinceList" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
        
      <el-form-item
        :prop=" props.prop + '.' + customKey.city"
        :rules="[{ required: true, message: '请选择市', trigger: 'change', }]"
      >
        <el-select
          ref="cityLabel"
          v-model="formData[customKey.city]"
          placeholder="选择市"
          :disabled="readonly"
          @change="cityChange($event)"
        >
          <el-option v-for="item in cityList" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
        
      <el-form-item
        :prop=" props.prop + '.' + customKey.area"
        :rules="[{ required: true, message: '请选择区县', trigger: 'change', }]"
      >
        <el-select
          ref="areaLabel"
          v-model="formData[customKey.area]"
          placeholder="选择区县"
          :disabled="readonly"
          @change="setDetailAddress"
        >
          <el-option v-for="item in areaList" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
        
      <el-form-item
        :prop=" props.prop + '.' + customKey.detailAddress"
        :rules="[{ required: true, message: '请输入详细地址', trigger: 'change', }]"
      >
        <el-input v-model="formData[customKey.detailAddress]" placeholder="详细地址" :disabled="readonly" />
      </el-form-item>
    </el-form-item>
  </el-col>
</template>

<script lang="ts" setup>
/**
* 省市区组件
* @prop formData  表单form的json对象，{province, city, area, detailAddress, ...}
* @prop customKey 自定义属性的key
*          [default {
              province: 'province', city: 'city', area: 'area', detailAddress: 'detailAddress'
          }] 
* @prop span [default 24] 组件是以el-col开始，该属性是el-col上的span属性
* @prop label [default '地址:'] 标题
* @method initAddress 初始化数据方法
*/
import { ref, onMounted, nextTick } from 'vue';
import { getListByParentCode } from '@/api/article';

const props = defineProps({
  state: {
    type: String,
    default: ''
  },
  formData: {
    type: Object,
    required: true
  },
  span: {
    type: Number,
    default: 24
  },
  label: {
    type: String,
    default: '地址:'
  },
  prop: {
    type: String,
    default: ''
  },
  required: Boolean,
  customKey: {
    type: Object,
    default() {
      return {
        province: 'province', city: 'city', area: 'area', detailAddress: 'detailAddress'
      }
    }
  }
})

// 是否只读
const readonly = ref(false)
readonly.value = (props.state == 'check')

const cityList = ref([]);
const areaList = ref([]);

const provinceList = ref([])

const getProvinceList = () => {
  if (provinceList.value.length) {
    return
  }
  getListByParentCode({ parentCode: 100000 })
  .then((res: any) => {
    provinceList.value = res.data;
  })
  .catch((err: any) => {
    console.error(err.msg)
  });
}

onMounted(async () => {
  await getProvinceList()
});

const setDetailAddress = () => {
  let result = '';
  // console.log('result', result)
  if (props.formData[props.customKey.province]) {
      result += provinceList.value.find(item => item.code === props.formData[props.customKey.province])?.name || '';
  }
  if (props.formData[props.customKey.city]) {
      result += cityList.value.find(item => item.code === props.formData[props.customKey.city])?.name || '';
  }
  if (props.formData[props.customKey.area]) {
      result += areaList.value.find(item => item.code === props.formData[props.customKey.area])?.name || '';
  }
  // console.log('result', result)
  // props.formData[props.customKey.detailAddress] = result;
}

const provinceChange = (e: string | number, notReset: boolean) => {
  if (!notReset) {
    props.formData[props.customKey.city] = '';
    cityList.value = [];
    props.formData[props.customKey.area] = '';
    areaList.value = [];
    nextTick(() => {
        setDetailAddress();
    })
  }
  return new Promise((resolve) => {
    getListByParentCode({ parentCode: e }).then((res) => {
      cityList.value = res.data;
      resolve();
    });
  })
};

const cityChange = (e: string | number, notReset: boolean) => {
  if (!notReset) {
    props.formData[props.customKey.area] = '';
    areaList.value = [];
    nextTick(() => {
      setDetailAddress();
    })
  }
  return new Promise((resolve) => {
    getListByParentCode({ parentCode: e }).then((res) => {
      areaList.value = res.data;
      resolve();
    });
  })
};

const initAddress = async () => {
// console.log('props.formData', props.formData, 'props.customKey', props.customKey)
// console.log('province', props.formData[props.customKey.province])
  if (!props.formData[props.customKey.province]) return false;
  await provinceChange(props.formData[props.customKey.province], true);
  // console.log('city', props.formData[props.customKey.city])
  if (!props.formData[props.customKey.city]) return false;
  await cityChange(props.formData[props.customKey.city], true);
}

defineExpose({ initAddress });

</script>

<style lang="scss" scoped>
.address-wrapper {
  :deep(.el-form-item__content) {
    display: flex;
    .el-form-item {
      flex-basis: 16%;
      margin-right: 10px;
    }
    :last-child {
      flex: 1;
      width: auto;
      margin-right: 0;
    }
  }
}
</style>